package com.imddysc.spbbatchjoblauncher;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component("jobLauncherCommandRunner")
public class JobLauncherCommandRunner implements CommandLineRunner {

	private static final Logger logger = LoggerFactory.getLogger(JobLauncherCommandRunner.class);

	@Autowired
	private JobLauncher jobLauncher;

	@Autowired
	private Job helloWorldJob;

	@Override
	public void run(String... args) throws Exception {
		try {
			JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
			jobParametersBuilder.addDate("timestamp ", new Date());
			JobExecution execution = jobLauncher.run(helloWorldJob, jobParametersBuilder.toJobParameters());
			System.out.println("Execution status: " + execution.getStatus());
		} catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException | JobParametersInvalidException e) {
			e.printStackTrace();
		}

	}

}
